package org.jeecg.lawcase.data.reader.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.lawcase.data.reader.DataImportApadter;
import org.jeecg.lawcase.data.reader.DataImportManager;
import org.jeecg.lawcase.data.reader.DataTemplate;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Component
public class TextDataImportImpl2 implements DataImportApadter {

    public TextDataImportImpl2() {
        DataImportManager.registerService(this.getFileType(), this);
    }

    private DataTemplate dataTemplate = new DataTemplate();

    @Override
    public String getFileType() {
        return "txt2";
    }

    @Override
    public DataTemplate importData(String fileName, InputStream inputStream) {
        String line = null;
        int lineIndex = 0;
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
            while (StringUtils.isNotBlank(line = br.readLine())) {
                if(lineIndex == 0){
                    if(!(line.contains("账户状态") && line.contains("注册身份证号"))){
                        break;
                    }
                }
                lineIndex ++;
                if(dataTemplate.getHeaders().size() > 0 && (line.contains("账户状态") && line.contains("注册身份证号"))){
                    continue;
                }
                if((line.contains("注销信息"))){
                    break;
                }
                // 按行读取数据
                if(dataTemplate.getHeaders().size() == 0){
                    this.setHeader(dataTemplate, line);
                } else {
                    this.addRow(dataTemplate, line);
                }
            }
        } catch (Exception e){
            throw new JeecgBootException(e);
        }
        return dataTemplate;
    }

    /**
     * 读取文件头
     * @param dataTemplate
     * @param line
     */
    public void setHeader(DataTemplate dataTemplate, String line){
        String[] titles = line.split("\t");
        for(String title: titles){
            if(title.contains("分") && (title.contains("金额") || title.contains("余额"))){
                title = title.replace("分", "元");
            }
            dataTemplate.getHeaders().add(title);
        }
    }

    public DataTemplate getDataTemplate() {
        return dataTemplate;
    }

    private BigDecimal money2 = new BigDecimal(100);

    /**
     * 读取数据内容
     * @param dataTemplate
     * @param line
     */
    public void addRow(DataTemplate dataTemplate, String line){
        String[] datas = line.split("\t");
        List<String> row = new ArrayList<>();
        for(int i=0; i<datas.length; i++){
            String data = datas[i];
            String header = dataTemplate.getHeaders().get(i);
            if(StringUtils.isNotBlank(data) && header.contains("元") && (header.contains("金额") || header.contains("余额"))){
                BigDecimal money1 = new BigDecimal(data);
                BigDecimal result = money1.divide(money2, 2, RoundingMode.DOWN);
                data = result.toString();
            }
            row.add(data);
        }
        dataTemplate.getDatas().add(row);
    }

    public static void main(String[] args) throws FileNotFoundException {
        TextDataImportImpl2 textDataImport = new TextDataImportImpl2();
        String basePath = "D:\\Workspace\\projects\\owner\\YunDing\\数据资料\\0927\\";
        String targetPath = "D:\\";
        treeFile(textDataImport, basePath, targetPath);
        parseFile(textDataImport, "D:\\个人注册信息汇总.xlsx");
    }

    private static void treeFile(TextDataImportImpl2 textDataImport, String basePath, String targetPath) throws FileNotFoundException {
        File[] files = new File(basePath).listFiles();
        if(files != null){
            for(File file: files){
                String curPath = targetPath + file.getName();
                if(file.isFile()){
                    System.out.println("file.getPath()=" + file.getPath());
                    textDataImport.importData("TenpayTrades.txt", new FileInputStream(file.getPath()));
                } else {
                    treeFile(textDataImport, file.getPath(), curPath + "\\");
                }
            }
        }
    }

    private static void parseFile(TextDataImportImpl2 textDataImport, String targetPath) throws FileNotFoundException {
        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet("微信数据");
        Row row = sheet.createRow(0);
        for(int i=0; i<textDataImport.dataTemplate.getHeaders().size(); i++){
            String item = textDataImport.dataTemplate.getHeaders().get(i);
            Cell cell = row.createCell(i);
            cell.setCellValue(item);
        }

        int startRow = 1;
        for(List<String> items: textDataImport.dataTemplate.getDatas()){
            row = sheet.createRow(startRow);
            for(int i=0; i<items.size(); i++){
                String item = items.get(i);
                Cell cell = row.createCell(i);
                cell.setCellValue(item);
            }
            startRow ++;
        }
        File targetFile = new File(targetPath);
        if(!targetFile.getParentFile().exists()){
            targetFile.getParentFile().mkdirs();
        }

        // 写入文件
        try (FileOutputStream outputStream = new FileOutputStream(targetFile)) {
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 清理资源
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
